package com.source.app.selenium;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import com.source.utils.Utils;

public class LoginAction {
	
	/**
	 * 登录京东
	 * @param uname
	 * @param pword
	 * @return
	 */
	public static String login(String uname, String pword) {
		String path = "/Users/admin/chromedriver/geckodriver";
		System.setProperty("webdriver.gecko.driver", path);
		FirefoxOptions options = new FirefoxOptions();
		options.setLegacy(false);
		FirefoxDriver webDriver = new FirefoxDriver(options);
		webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		webDriver.get("https://m.jd.com/");
		webDriver.findElement(By.id("index_searchLogin")).click();
		sleep(2);
		WebElement username = webDriver.findElement(By.xpath("//input[@id='username']"));
		username.clear();
		username.sendKeys(uname);
		WebElement password = webDriver.findElement(By.xpath("//input[@id='password']"));
		password.clear();
		password.sendKeys(pword);
		webDriver.findElement(By.id("loginBtn")).click();
		String notice = webDriver.findElement(By.className("notice")).getText();
		System.out.println(notice);
		if (!Utils.isEmpty(notice)) {
			webDriver.quit();
			return null;
		}
		// 获取cookie
		Set<Cookie> cookies = webDriver.manage().getCookies();
		Iterator<Cookie> iterator = cookies.iterator();
		String cookieString = "";
		while (iterator.hasNext()) {
			cookieString+=iterator.next().toString()+";";
		}
		// 关闭浏览器
		try {
//			webDriver.close();
			webDriver.quit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cookieString;

	}

	

	/**
	 * 睡眠
	 * 
	 * @param i
	 *            单位 秒
	 */
	private static void sleep(int i) {
		try {
			Thread.sleep(i * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
